'use strict'

const { Controller } = require('egg')

class KujoMiva extends Controller {
    /**
    * @api {get} /KujoMiva 获取列表
    * @apiGroup KujoMiva
    */
    async index() {
        const { ctx } = this
        const { proid: pro_id } = ctx.header

        const result = await this.app.databaseWuye.select('contact', {
            where: { pro_id },
            orders: [['id', 'desc']]
        })

        ctx.returnBody(200, '进入了获取列表接口', result)
    }

    /**
    * @api {post} /KujoMiva 创建数据
    * @apiGroup KujoMiva
    */
    async create() {
        const { ctx } = this
        const {
            tel = '新增电话',
            add = '新增地址',
            mail = '新增邮箱',
        } = ctx.request.body
        const { proid: pro_id } = ctx.header

        const result = await this.app.databaseWuye.insert('contact', {
            tel,
            add,
            mail,
            pro_id
        })

        ctx.returnBody(200, '添加联系方式成功', {
            id: result.insertId
        })
    }

    /**
    * @api {put} /KujoMiva/:id 更改数据
    * @apiGroup KujoMiva
    */
    async update() {
        const { ctx } = this
        const { id } = ctx.params

        await this.app.databaseWuye.beginTransactionScope(async conn => {
            const oldData = await conn.get('contact', { id })
            const {
                tel = oldData.tel,
                add = oldData.add,
                mail = oldData.mail
            } = ctx.request.body
            const updateRow = {
                tel,
                add,
                mail,
            }
            await conn.update('contact', updateRow, { where: { id } })
        })
        ctx.returnBody(200, '联系方式修改成功')
    }

    /**
    * @api {delete} /KujoMiva/:id 删除数据
    * @apiGroup KujoMiva
    */
    async destroy() {
        const { ctx } = this
        const { id } = ctx.params

        const result = await this.app.databaseWuye.delete('contact', {
            id
        })

        ctx.returnBody(200, '删除成功', result)
    }
}

module.exports = KujoMiva
